import axios from 'axios'
import store from '../store'
import QS from 'qs'
import {
  Loading,
  Message
} from 'element-ui'
import { getToken } from '@/utils/auth'

let loading = ''
let flag = 0
const CancelToken = axios.CancelToken
const source = CancelToken.source()
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 15000,
  cancelToken: source.token
})
// 不展示loading的请求url
const noLoadingReq = ['/dict/selectByType']
let tokenUrl = [
  '/MMM/dataSource/findInterfaceList'
]
service.interceptors.request.use(function (config) {
  flag++
  if (tokenUrl.includes(config.url)) {
    config.data = config.data ? config.data : {}
    config.data.token = getToken()
  }
  if (config.method === 'get' && config.data) {
    config.url = config.url + '?' + QS.stringify(config.data)
  }
  if (noLoadingReq.indexOf(config.url) === -1) {
    loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  return config
}, function (error) {
  return Promise.reject(error)
})


service.interceptors.response.use(function (response) {
  flag--
  if (!flag && loading) {
    loading.close()
  }
  // if (!response.data.success && response.data.data === 'ErrorToLogin') {
  if (!response.data.success && response.data.message === 'invalid token') {
    Message.error(response.data.message)
    store.dispatch('LogOut')
  }
  return response
}, function (error) {
  flag--
  if (loading) {
    loading.close()
  }
  Message.error(error.request.statusText)
  return Promise.reject(error)
})
export default service
